package Threads.ReentrantLock;

import Threads.Utils.log;

import java.util.concurrent.locks.ReentrantLock;


//测试可打断
public class interrputTest {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock=new ReentrantLock();

        new Thread(()->{
            try {
                log.debug("i got the lock");
                lock.lock();
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                log.debug("i will release the lock");
                lock.unlock();
            }
        }).start();

        //测试lock方法，lock方法是不可以被打断的
        /*Thread t=new Thread(()->{
           try{
               lock.lock();
               log.debug("i got the lock");
               log.debug(Thread.currentThread().isInterrupted());
           }finally {
               lock.unlock();
           }
        });

        Thread.sleep(100);
        t.start();
        Thread.sleep(1000);
        t.interrupt();*/

        //测试可打断
        Thread t=new Thread(()->{
            try{
                lock.lockInterruptibly();
                log.debug("i got the lock");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //因为这时候没有获得锁，但还调用了unlock方法，所以会报illegalmonitorstateexception
                lock.unlock();
            }
        });

        Thread.sleep(100);
        t.start();
        Thread.sleep(1000);
        //执行这里的时候，t所在线程会直接报异常
        t.interrupt();
    }
}
